import {defineStore} from 'pinia'
import OSS from 'ali-oss'
import {generateCredentialsApi} from '@/api/system/oss.api'

export const useOssStore = defineStore('oss', {
	state(): {
		ossClient?: OSS
	} {
		return {
			ossClient: undefined
		}
	},
	actions: {
		async initOssClient() {
			try {
				if (this.ossClient) {
					return Promise.resolve()
				} else {
					const credentials = (await generateCredentialsApi()).data
					this.ossClient = new OSS({
						region: credentials.region,
						bucket: credentials.bucket,
						accessKeyId: credentials.accessKeyId,
						accessKeySecret: credentials.accessKeySecret,
						stsToken: credentials.securityToken,
						secure: true,
						refreshSTSToken: async () => {
							const newCredentials = (await generateCredentialsApi()).data
							return {
								region: newCredentials.region,
								bucket: newCredentials.bucket,
								accessKeyId: newCredentials.accessKeyId,
								accessKeySecret: newCredentials.accessKeySecret,
								stsToken: newCredentials.securityToken
							}
						},
						// 刷新临时访问凭证的时间间隔，单位为毫秒，此处设置为59分钟（临时身份有效期为1小时）
						refreshSTSTokenInterval: 1000 * 60 * 59
					})
					return Promise.resolve()
				}
			} catch (e) {
				return Promise.reject(e)
			}
		},
		resetOssStore() {
			this.ossClient = undefined
		}
	},
	persist: false
})
